package org.znxs.znagent_s.rag.tools;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 适用于 ai—agent 终端操作工具类
 */
@Slf4j
public class TerminalOperationTool {

    @Tool(description = "执行终端操作命令")
    public String executeTerminalCommand(@ToolParam(description = "") String command) {
        StringBuilder output = new StringBuilder();
        try {

            // windows系统使用这行代码
            Process process;
            String os = System.getProperty("os.name");
            log.info("操作系统为：{}", os);
            if ("Windows".equals(StrUtil.split(os, " ").getFirst())) {
                // windows 操作系统使用这套代码
                log.info("使用Windows 操作系统");
                ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
                process = builder.start();
            } else {
                // linux 系统使用这行代码
                log.info("使用其他 操作系统");
                process = Runtime.getRuntime().exec(StrUtil.splitToArray(command, " "));
            }


            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                // 判断是否为最后一行
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }
            int exitCode = process.waitFor();
            // 若执行状态码为空，直接添加错误状态码提示
            if (exitCode != 0) {
                log.warn("错误状态码：\n{}", exitCode);
                output.append("Command execution failed with exit code: ").append(exitCode);
            }
            log.info("命令执行成功：\n{}", output);
        } catch (IOException | InterruptedException e) {
            // 出现异常则添加提示报错
            log.info("命令执行失败：\n", e);
            output.append("Error executing command: ").append(e.getMessage());
        }
        return output.toString();
    }

}
